﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using RestSharp;

namespace ComicIsland.App.Views
{
    public partial class CommunityReviewUserPage : PhoneApplicationPage
    {
        private bool IsNeedReloadData = false;
        private string userId = string.Empty;
        JsonComicCommunityReviewInfo currentSelectedItem;
        private bool IsLastPage = false;
        private int pageIndex = 1;
        // 数据加载的标识
        public bool IsLoading = false;
        // 线程锁的对象
        private object o = new object();

        public CommunityReviewUserPage()
        {
            InitializeComponent();
            this.IsNeedReloadData = true;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            this.IsNeedReloadData = false;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            base.NavigationContext.QueryString.TryGetValue("userId", out userId);
            if (string.IsNullOrWhiteSpace(userId))
            {
                base.NavigationService.GoBack();
                return;
            }
            if (IsNeedReloadData)
                LoadData(userId);
        }


        public void LoadData(string userId, int pageIndex = 1)
        {
            this.psbStatus.OpenStatusBar(AppResources.DataLoading);
            //getuserdiscusslist?userid=1&pageno=1&pagesize=20
            string requestUrl = string.Concat(KEYS.REQUEST_HOST,
                string.Format("/comic/getuserdiscusslist?userid={0}&pageno={1}&pagesize=20&e={2}", userId, pageIndex, DateTime.Now.Ticks), "&", KEYS.REQUEST_QUERY_PLATFORM);
            LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());

            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonComicCommunityReview>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null && rootCharacterString.Info.Count > 0))
                {
                    MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    var items = rootCharacterString.Info;
                    if (items != null && items.Count > 0)
                    {
                        BindData(items);
                    }
                }
                this.psbStatus.CloseStatusBar();
                return;
            }

            //var client = new RestClient(requestUrl);
            //var rest = new RestRequest(Method.GET);
            //client.ExecuteAsync(rest, (response) =>
            //{
            //    var result = response.Content;
            //});

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //

                        if (result.IndexOf("\"info\":{}") >= 0)
                        {
                            IsLastPage = true;
                            if (pageIndex > 1)
                            {
                                //加载更多时给予的提示
                            }
                            else
                            {
                                //搜索结果为空时可能会出现“data”：{”items“:{}} 注意这不是[]
                                MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                            }
                            return;
                        }
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicCommunityReview>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null && rootCharacterString.Info.Count > 0))
                        {
                            MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            var items = rootCharacterString.Info;
                            if (items != null && items.Count > 0)
                            {
                                //cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                                BindData(items);
                            }
                        }
                        #endregion 获取结果处理
                    }
                    catch (Exception err)
                    {

                    }
                    finally
                    {
                        this.psbStatus.CloseStatusBar();
                    }
                });
            }, webTask);
        }

        void BindData(ObservableCollection<JsonComicCommunityReviewInfo> items)
        {
            if (!(items != null && items.Count > 0))
                return;

            this.Dispatcher.BeginInvoke(() =>
            {
                if (pageIndex > 0)
                {
                    if (this.lls.ItemsSource != null && this.lls.ItemsSource.Count > 0)
                    {
                        foreach (var item in items)
                        {
                            this.lls.ItemsSource.Add(item);
                        }
                    }
                    else
                    {
                        this.lls.ItemsSource = items;
                    }
                }
                else
                {
                    this.lls.ItemsSource = items;
                }
            });
        }

        private void lls_ItemRealized(object sender, ItemRealizationEventArgs e)
        {
            lock (o)
            {
                if (IsLoading)
                    return;
                if (e.ItemKind != LongListSelectorItemKind.Item)
                    return;
                currentSelectedItem = e.Container.Content as JsonComicCommunityReviewInfo;
                int selectedIndex = this.lls.ItemsSource.IndexOf(currentSelectedItem);
                int total = this.lls.ItemsSource.Count;
                if (total - selectedIndex <= 2)
                {
                    // 设置IsLoading为true，在加载数据的过程中，禁止多次进入
                    IsLoading = true;
                    if (IsLastPage)
                    {
                        //this.statusBar.OpenStatusBar(AppResources.DataNoMore);
                        //this.statusBar.CloseStatusBar();
                        MessageToastManager.Show(AppResources.DataNoMore);
                        // 修改加载的状态
                        IsLoading = false;
                    }
                    else
                    {
                        this.pageIndex += 1;
                        this.LoadData(this.userId, pageIndex);
                        // 修改加载的状态
                        IsLoading = false;
                    }
                }
            }
        }

        private void llsGrid_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = ((sender as Grid).DataContext as JsonComicCommunityReviewInfo);
            if (item == null)
                return;

            this.lls.SelectedItem = item;
            NaviService.Navigate(ComicIslandPage.CommunityDetailPage, string.Concat("?comicId=", item.Id));
        }

        private void llsGrid_ManipulationDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            e.Complete();
            if (e.CumulativeManipulation.Translation.Y > 0)
            {
                //从下往上拉时不处理
                return;
            }

            if (IsLastPage)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    Helper.PageShowDataNoMore<JsonComicCommunityReviewInfo>(sender, this.lls);
                });
            }
        }



    }
}